<?php
namespace Modules\Payment\Entities;

use Modules\Payment\Entities\PaymentRecord;

use ThrowException;
use ByteDance;
use Cache;

use SimpleXMLElement;

use Modules\Core\Helpers\HttpClient;

// use HttpResponse;

class ZhongjinPay
{
	protected $clientName;
	protected $payType;
	protected $pay;
	protected $app;

	public function __construct($clientName, $payType)
	{
		// $this->app = ByteDance::get();
		// $this->pay = $this->app->payment;
		// $this->payType = $payType;
		// $this->clientName = $clientName;
	}

	public function __call($name, $arguments)
    {
    	return call_user_func_array(array($this->pay, $name), $arguments);
    }

    // 配置支付项
	public function config($user, $order)
	{
		$money = $order->payPrice();

		if ($order->type === 'box') {
			$title = '购买盲盒';
		}
		else {
			$title = $order->title();
		}

		$title  = '10';

		$number = $order->payNumber();

		$openId = $user->getOpenid('miniapp', $this->clientName);
		$openId = "wx8888888888";

		$uuid = $order->uuid;
		$body = $title;

		$info = [
			'out_order_no' => $number,
			'total_amount' => $money,
			'openid' => $openId,
			'subject' => $title,
			'body' => $body,
			'valid_time' => 300,
			'cp_extra' => $uuid,
			'notify_url' => env('APP_URL') . '/payment-callback/byte-dance',
			'disable_msg' => 0,
		];

		return  $this->precreateOrder($info, $order);

		// return $this->pay->pay($uuid, $number, $money,  $title, [
		// 	'body' => '测试商品',
		// 	'notify_url' => 'https://baidu.com/'
		// ]);
	}

	// 预创建订单
	public function precreateOrder($info, $order)
	{
		$rootDir  = base_path() . "/customVendor/zhongjinPay";

		require( $rootDir . "/txtype.php"); 
	    require($rootDir . "/payment.php");

		// 1.取得参数
	    $institutionID = '007332';
	    $paymentNo = $info['out_order_no'] . '_' . rand(0, 9999);
	    $redirectSource = 40;
	    $payWay = 51;
	    $payType = 31;
	    $bankID = '';
	    $userID = '';
	    $amount = $info['total_amount'];
	    $limitPay = 10;
	    $settlementFlag = '0001';
	    $splitType = 10;
	    $platformName = '红叉盲盒';
	    // $goodsName = $info['subject'];
	    $goodsName = 10;

	    $clientIP = '127.0.0.1';
	    $appID = env('MINIAPP_APPID');
	    $openID = $info['openid'];
	    $installmentType = 10;
	    $feeMode = 10;
	    $accountNumber = '';
	    $numberOfInstallments = '';
	    $expirePeriod = 10;
	    $pageUrl = '';
	    $remark = '';
	    $Extension = '';
	    $GoodsTag = '';

	        
	    $simpleXML= new SimpleXMLElement($xmltx2101);   
	    
	    // 4.赋值
	    $simpleXML->Body->InstitutionID=$institutionID;
	    $simpleXML->Body->PaymentNo=$paymentNo;
	    $simpleXML->Body->RedirectSource=$redirectSource;
	    $simpleXML->Body->PayWay=$payWay;
	    $simpleXML->Body->PayType=$payType;
	    $simpleXML->Body->BankID=$bankID;
	    $simpleXML->Body->UserID=$userID;
	    $simpleXML->Body->Amount=$amount;
	    $simpleXML->Body->LimitPay=$limitPay;
	    $simpleXML->Body->SettlementFlag=$settlementFlag;
	    $simpleXML->Body->SplitType=$splitType;
	    $simpleXML->Body->PlatformName=$platformName;
	    $simpleXML->Body->GoodsName=$goodsName;
	    $simpleXML->Body->ClientIP=$clientIP;
	    $simpleXML->Body->AppID=$appID;
	    $simpleXML->Body->OpenID=$openID;
	    $simpleXML->Body->InstallmentType=$installmentType;
	    $simpleXML->Body->FeeMode=$feeMode;
	    $simpleXML->Body->AccountNumber=$accountNumber;
	    $simpleXML->Body->NumberOfInstallments=$numberOfInstallments;
	    $simpleXML->Body->ExpirePeriod=$expirePeriod;
	    $simpleXML->Body->PageUrl=$pageUrl;
	    $simpleXML->Body->Remark=$remark;
	    $simpleXML->Body->Extension=$Extension;
	    $simpleXML->Body->GoodsTag=$GoodsTag;

	    // \Log::error($simpleXML->Body);
		
		$xmlStr = $simpleXML->asXML();	

		// \Log::error($xmlStr);

		$signature=cfcasign_pkcs12(trim($xmlStr));	
		if(isDgEnv=="NO")
        {
            // echo "非数字信封";
            $message=base64_encode(trim($xmlStr));
            $response=cfcatx_transfer($message,$signature); 
            $plainText=trim(base64_decode($response[0]));
            $ok=cfcaverify($plainText,$response[1]);
            if($ok!=1)
            {
                \Log::error('验签失败. ' . $order->id);
                ThrowException::Conflict('验签失败~');
            }else{  
            	// \Log::error($response);

            	// exit();

                $simpleXML= new SimpleXMLElement($plainText);  

                if (!$simpleXML->Body->AuthCode)  {
                    $xmlStr = $simpleXML->asXML();	
                    \Log::error('获取支付配置失败. ' . $order->id);
        		    \Log::error($xmlStr);
                    ThrowException::Conflict('获取支付配置失败~');
                }

                return json_decode($simpleXML->Body->AuthCode, true);
            }
        }
	}

	public function checkStatus($order)
	{
		$rootDir  = base_path() . "/customVendor/zhongjinPay";

		require($rootDir . "/txtype.php"); 
	    require($rootDir . "/payment.php");

		// 1.取得参数
	    $institutionID = env('INSTITUTION_ID');
	    $paymentNo = $_POST["PaymentNo"];
		$SourceTxTime = $_POST["SourceTxTime"];
		
		$simpleXML= new SimpleXMLElement($xmltx2102);	
		
		// 4.赋值
		$simpleXML->Head->InstitutionID=$institutionID;
		$simpleXML->Body->PaymentNo=$paymentNo;
		$simpleXML->Body->SourceTxTime=$SourceTxTime;
		
		$xmlStr = $simpleXML->asXML();	
		$signature=cfcasign_pkcs12(trim($xmlStr));
		if(isDgEnv=="NO")
		{
			echo "非数字信封";
			$message=base64_encode(trim($xmlStr));
			$response=cfcatx_transfer($message,$signature);	
			$plainText=trim(base64_decode($response[0]));
			$ok=cfcaverify($plainText,$response[1]);
			if($ok!=1)
			{
				$errInfo="验签失败";
			
				require("error.php");
			}else{	
				$simpleXML= new SimpleXMLElement($plainText);	
				$txName="跳转支付订单查询";
				$txCode="2102";
				require("response.php");
			}
		}
	}

	// 检验回调结果
	public function checkCallbackData($req)
	{
		$rootDir  = base_path() . "/customVendor/zhongjinPay";

		require($rootDir . "/txtype.php"); 
	    require($rootDir . "/payment.php");

	    $message = $req->message;
	    $signature = $req->signature;
	    $encryptSN = $req->encryptSN;
	    $isDgEnv = $req->isDgEnv;
	    $digitalEnvelope = $req->digitalEnvelope;
	    $signAlgorithm = $req->signAlgorithm;
	    $signSN = $req->signSN;

	    $plainText=null;
		if($isDgEnv=="YES"){
			print_r("<br>&&&&&&响应随机秘钥if里的：".$message."结束");
			$plainText=process_decrypt($message,trim($signature),$signAlgorithm,$signSN,$encryptSN,$digitalEnvelope);

		}else{
			$plainText=base64_decode($message);	
		}

		$ok = cfcaverify($plainText,$signature);

		if ($ok != 1)
		{
			// 验签失败 
			return false;
		}
		else {
			// 验签成功
    		return $plainText;
		}

	}


	public function refundMoney($order, $refundMoney = null, $options = []) 
	{
		// $payment = $order->payment() ?: ThrowException::Conflict('订单无支付记录');

		// \Log::error($payment);
		// exit();

		// $orderType = 'single_order';

		// $remark = @v($options['remark'], '订单退款');

		// // $paymentRecord = $order->payment();
		// $number = $order->pay_number;

		// // \Log::error($number);
		// // exit();

		// $info = [
		// 	'out_trade_no' => $number,
		// 	'out_refund_no' => time(),
		// 	'total_fee' => $order->pay_money_price,
		// 	'refund_fee' => $refundMoney,
		// 	'refund_desc' => $remark,
		// ];

		// try {
		// 	$res = $this->pay->refund($info);
		// }
		// catch(\Yansongda\Pay\Exceptions\GatewayException $e) {
		// 	\Log::error('订单: ' . $order->id . ' 退款失败:' . $e->getMessage());
		// 	ThrowException::Conflict('退款失败, 请检查退款金额是否超出总订单金额');
		// }
	}


	public function recordPayment($order, $clientName, $paySubType, $data, $options = [])
	{
		$info = [
			'trade_number' => @$data['transaction_id'],
			'out_trade_number' => @$data['out_trade_no'],
			'client_name' => $clientName,
			'pay_type' => 'wechat',
			'pay_sub_type' => @$paySubType,
			'paid_at' => @$data['time_end'],
			'money' => @$data['total_fee'] ?: $order->pay_money_price,
			'status' => 2,
			'options' => $data
		];

		if ($order->number[0] == 'U') 
			$info['union_order_id'] = $order->id;
		else
			$info['order_id'] = $order->id;

		$record = PaymentRecord::create($info);

		$record->save();
	}

	public function success()
	{
		$rootDir  = base_path() . "/customVendor/zhongjinPay";
		require($rootDir . "/txtype.php"); 

		$responseXML= new SimpleXMLElement($xmlNotification);
		$responseXML->Head->Code = "2000";
		$responseXML->Head->Message = "OK.";

		$responseXMLStr = $responseXML->asXML();
		$base64Str = base64_encode(trim($responseXMLStr));

		return $base64Str;
	}
}
